package cn.xjt.TcpFileLoadOptimized;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author xujiangtao
 * @create 2020-08-04-15:10
 */
public class ServerFileUpload {
    public static void main(String[] args) throws IOException {

        ServerSocket server = new ServerSocket(9999);
        System.out.println("等待客户端连接");
        while (true)
        {
            String FileName = "xujiangtao"+System.currentTimeMillis()+".jpg";
            //服务器上传的地址
            FileOutputStream fileOutputStream = new FileOutputStream(new File("E:\\tupian\\"+FileName));
            Socket client = server.accept();
            System.out.println("连接成功");
            //开启多个线程
            new Thread(()->{
                try {
                    //连接成功
                    InputStream serIS = client.getInputStream();
                    byte[] data = new byte[5000];
                    int lenght = -1;
                    System.out.println("数据正在上传...");
                    while ((lenght=serIS.read(data))!=-1)
                    {
                        fileOutputStream.write(data,0,lenght);
                    }
                    System.out.println("数据已经上传成功");
                    //成功回馈
                    OutputStream os = client.getOutputStream();
                    os.write("上传成功".getBytes());
                }catch (IOException e)
                {
                    System.out.println(e);
                }
            }).start();

        }

    }
}